package Pet.Management.service.impl;

import Pet.Management.domain.entity.Comment;
import Pet.Management.domain.entity.Message;
import Pet.Management.domain.entity.Post;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.MessageRepository;
import Pet.Management.repository.PostRepository;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.MessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public Message sendPrivateMessage(Long senderId, Long receiverId, String title, String content) {
        Optional<User> receiverOpt = userRepository.findById(receiverId);
        if (!receiverOpt.isPresent()) {
            throw new IllegalArgumentException("接收者不存在");
        }

        Message message = new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setTitle(title);
        message.setContent(content);
        message.setIsRead(false);
        message.setType("private");
        message.setCreateTime(LocalDateTime.now());

        try {
            Map<String, Object> extra = new HashMap<>();
            if (senderId != null && senderId != 0) {
                Optional<User> senderOpt = userRepository.findById(senderId);
                if (senderOpt.isPresent() && senderOpt.get().getAvatar() != null && !senderOpt.get().getAvatar().isEmpty()) {
                    extra.put("avatar", senderOpt.get().getAvatar());
                }
            }
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }

        return messageRepository.save(message);
    }

    @Override
    @Transactional
    public Message sendSystemNotification(Long receiverId, String title, String content) {
        Optional<User> receiverOpt = userRepository.findById(receiverId);
        if (!receiverOpt.isPresent()) {
            throw new IllegalArgumentException("接收者不存在");
        }

        Message message = new Message();
        message.setReceiverId(receiverId);
        message.setTitle(title);
        message.setContent(content);
        message.setIsRead(false);
        message.setType("system");
        message.setCreateTime(LocalDateTime.now());
        message.setExtra("{}");

        return messageRepository.save(message);
    }

    @Override
    @Transactional
    public Message sendLikeNotification(User liker, Long postId) {
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            throw new IllegalArgumentException("帖子不存在");
        }

        Post post = postOpt.get();
        User postAuthor = post.getUser();

        if (liker.getId().equals(postAuthor.getId())) {
            return null; // 不给自己发送点赞通知
        }

        Message message = new Message();
        message.setSenderId(liker.getId());
        message.setReceiverId(postAuthor.getId());
        message.setTitle("收到新点赞");
        message.setContent(liker.getUsername() + " 点赞了您的帖子《" + post.getTitle() + "》");
        message.setIsRead(false);
        message.setType("like");
        message.setCreateTime(LocalDateTime.now());

        try {
            Map<String, Object> extra = new HashMap<>();
            extra.put("postId", postId.toString());
            if (liker.getAvatar() != null && !liker.getAvatar().isEmpty()) {
                extra.put("avatar", liker.getAvatar());
            }
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }

        return messageRepository.save(message);
    }

    @Override
    @Transactional
    public Message sendFavoriteNotification(User favorer, Long postId) {
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            throw new IllegalArgumentException("帖子不存在");
        }

        Post post = postOpt.get();
        User postAuthor = post.getUser();

        if (favorer.getId().equals(postAuthor.getId())) {
            return null; // 不给自己发送收藏通知
        }

        Message message = new Message();
        message.setSenderId(favorer.getId());
        message.setReceiverId(postAuthor.getId());
        message.setTitle("收到新收藏");
        message.setContent(favorer.getUsername() + " 收藏了您的帖子《" + post.getTitle() + "》");
        message.setIsRead(false);
        message.setType("favorite");
        message.setCreateTime(LocalDateTime.now());

        try {
            Map<String, Object> extra = new HashMap<>();
            extra.put("postId", postId.toString());
            if (favorer.getAvatar() != null && !favorer.getAvatar().isEmpty()) {
                extra.put("avatar", favorer.getAvatar());
            }
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }

        return messageRepository.save(message);
    }

    @Override
    @Transactional
    public Message sendCommentNotification(Comment comment) {
        if (comment == null || comment.getPost() == null || comment.getUser() == null) {
            throw new IllegalArgumentException("评论信息不完整");
        }

        User commenter = comment.getUser();
        Post post = comment.getPost();
        User postAuthor = post.getUser();

        if (commenter.getId().equals(postAuthor.getId())) {
            return null; // 不给自己发送评论通知
        }

        Message message = new Message();
        message.setSenderId(commenter.getId());
        message.setReceiverId(postAuthor.getId());
        message.setTitle("收到新评论");
        message.setContent(commenter.getUsername() + " 评论了您的帖子《" + post.getTitle() + "》: " + comment.getContent());
        message.setIsRead(false);
        message.setType("comment");
        message.setCreateTime(LocalDateTime.now());

        try {
            Map<String, Object> extra = new HashMap<>();
            extra.put("postId", post.getId().toString());
            extra.put("commentId", comment.getId().toString());
            if (commenter.getAvatar() != null && !commenter.getAvatar().isEmpty()) {
                extra.put("avatar", commenter.getAvatar());
            }
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }

        return messageRepository.save(message);
    }

    @Override
    @Transactional
    public Message sendReplyNotification(Comment reply, Comment parentComment) {
        if (reply == null || parentComment == null || parentComment.getUser() == null) {
            throw new IllegalArgumentException("回复信息不完整");
        }

        User replier = reply.getUser();
        User commentAuthor = parentComment.getUser();
        Post post = reply.getPost();

        if (replier.getId().equals(commentAuthor.getId())) {
            return null; // 不给自己发送回复通知
        }

        Message message = new Message();
        message.setSenderId(replier.getId());
        message.setReceiverId(commentAuthor.getId());
        message.setTitle("收到新回复");
        message.setContent(replier.getUsername() + " 回复了您在《" + post.getTitle() + "》的评论: " + reply.getContent());
        message.setIsRead(false);
        message.setType("reply");
        message.setCreateTime(LocalDateTime.now());

        try {
            Map<String, Object> extra = new HashMap<>();
            extra.put("postId", post.getId().toString());
            extra.put("commentId", parentComment.getId().toString());
            extra.put("replyId", reply.getId().toString());
            if (replier.getAvatar() != null && !replier.getAvatar().isEmpty()) {
                extra.put("avatar", replier.getAvatar());
            }
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }

        return messageRepository.save(message);
    }

    @Override
    public Page<Message> getUserMessages(Long userId, Pageable pageable) {
        return messageRepository.findUserMessagesAndAnnouncements(userId, pageable);
    }

    @Override
    public long getUnreadMessageCount(Long userId) {
        return messageRepository.countByReceiverIdAndIsRead(userId, false);
    }

    @Override
    @Transactional
    public boolean markMessageAsRead(Long messageId, Long userId) {
        Optional<Message> messageOpt = messageRepository.findById(messageId);
        if (!messageOpt.isPresent()) {
            return false;
        }
        
        Message message = messageOpt.get();
        if (!message.getReceiverId().equals(userId)) {
            return false;
        }
        
        message.setIsRead(true);
        messageRepository.save(message);
        return true;
    }

    @Override
    @Transactional
    public boolean deleteMessage(Long messageId, Long userId) {
        Optional<Message> messageOpt = messageRepository.findById(messageId);
        if (!messageOpt.isPresent()) {
            return false;
        }
        
        Message message = messageOpt.get();
        if (!message.getReceiverId().equals(userId)) {
            return false;
        }
        
        messageRepository.delete(message);
        return true;
    }
} 